<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ApiController
 *
 * @author wangnaixin
 */

namespace Api\Controller;
use Think\Controller;

class ApiController extends Controller {

    //定义返回状态码
    public $EMPTY_CODE = 300;
    public $ERROR_CODE = -100;
    public $SUCCESS_CODE = 200;
    public $white_list = ['Login','House','Public','Common'];
    public $sysConfig;
    public $userLevelInfo;

    function __construct() {
        parent::__construct();
        $this->checkUser();
        $this->initConfig();
        $this->getUserLevel();

    }

    function _empty(){
        return $this->response('非法请求！',1);
    }

    public function callBack($msg,$code=200,$data=[]){
        $result = array(
            'msg'=>$msg,
            'code'=>$code,
            'data'=>$data
        );
        if (session('returnArray')) {
        	return $result;
        }
        if(IS_AJAX){
            $this->ajaxReturn($result);
        }else{
            if($code == $this->SUCCESS_CODE){
                return $data;
            }else{
                return false;
            }
        }
        
        
        
    }
    
    public function response($msg,$code=0,$data=array()){
    	$result = array(
    		'msg' => $msg,
    		'code' => $code,
    		'data' => $data
    	);
    	if (session('returnArray')) {
    		return $result;
    	}
    	if (IS_AJAX) {
    		$this->ajaxReturn($result);
    	}
    	return $result;
    }

    /**
     * 判断用户是否真实合法
     */
    private function checkUser(){
        if(!in_array(MODULE_NAME, $this->white_list)){
            //判断用户是否带有身份标示  根据身份标示 获取用户基本信息
        }
    }

    private function initConfig() {
        $configs = M('config')->select();
        foreach ($configs as $config) {
            $this->sysConfig[$config['key']] = $config['value'];
        }
    }

    private function getUserLevel() {
        $user_id = I('user_id');
        $level = '';
        $credit = M('users')->where(array('id' => $user_id))->getField('credit');
        for ($i=1;$i<=5;$i++) {
            if ($credit > $this->sysConfig['level_'.$i]) {
                $level = $i;
                break;
            }
        }
        $this->userLevelInfo = array(
            'user_level' => 'level_'.$level,
            'user_level_label' => $this->getCreditLabel('level_'.$level),
            'buyer_order_max' =>  $this->sysConfig['buyer_order_max_level_'.$level],
            'seller_order_max' =>  $this->sysConfig['seller_order_max_level_'.$level]
        );
    }

    // 获取信誉等级描述
    private function getCreditLabel($level='') {
        $levelLabels = array(
            'level_1' => '信誉极好',
            'level_2' => '信誉很好',
            'level_3' => '信誉较好',
            'level_4' => '信誉一般',
            'level_5' => '信誉差',
        );
        return $levelLabels[$level];
    }
}
